/**
 * Mermaid语法映射加载和验证工具
 * 专利协作写作平台 - 图形化拖拽功能模块
 */

import type {
    MermaidSyntaxMapping,
    ChartTypeMapping,
    FlowchartTemplates,
    ChartType,
    FlowchartTemplate
} from './types'

// import FlowChartMermaidSyntaxParser from './chart_type/flowchart'
import {FlowChartMermaidCodeGenerator,FlowChartMermaidSyntaxParser} from './chart_type/flowchart'

/**
 * 语法映射加载器
 * 单例模式，负责加载和缓存所有Mermaid语法映射配置
 */
export class SyntaxMappingLoader {
    private syntaxMapping: MermaidSyntaxMapping | null = null

    constructor() {
        this.syntaxMapping = null
    }

    /**
     * 加载所有语法映射配置
     */
    async loadMappings(): Promise<MermaidSyntaxMapping> {
        if (this.syntaxMapping) {
            return this.syntaxMapping
        }

        try {
            // 加载主配置文件 - 使用import而不是fetch
            const mainConfigModule = await import('./index.json')
            const mainConfig = mainConfigModule.default

            // 并行加载所有图表类型映射 - 使用import
            const chartMappings: ChartTypeMapping[] = []

            // 定义已知的图表类型映射文件
            const knownChartTypes = ['flowchart']

            for (const chartType of mainConfig.supportedChartTypes) {
                try {
                    // 只尝试加载已知存在的图表类型文件
                    if (knownChartTypes.includes(chartType)) {
                        // 使用具体的文件路径来避免Vite动态导入警告
                        let mappingModule
                        switch (chartType) {
                            case 'flowchart':
                                mappingModule = await import('./flowchart.json')
                                break
                            default:
                                console.warn(`Chart type "${chartType}" is not implemented yet, skipping...`)
                                continue
                        }
                        chartMappings.push(mappingModule.default as ChartTypeMapping)
                    } else {
                        console.warn(`Chart type "${chartType}" is not implemented yet, skipping...`)
                    }
                } catch (error) {
                    console.warn(`Failed to load chart mapping for ${chartType}:`, error)
                }
            }

            // 加载转换规则 - 使用import
            const conversionRulesModule = await import('./conversion-rules.json')
            const conversionRules = conversionRulesModule.default

            this.syntaxMapping = {
                ...mainConfig,
                supportedCharts: chartMappings,
                conversionRules: conversionRules as any // 暂时忽略类型错误
            }

            this.syntaxMapping.supportedCharts.map(chart => {
                chart.nodes = chart.nodes.reverse() // 确保节点类型按优先级降序排列
                chart.connections = chart.connections.reverse() // 确保连接类型按优先级降序排列
            })

            return this.syntaxMapping!
        } catch (error) {
            console.error('加载语法映射配置失败:', error)
            throw new Error('无法加载Mermaid语法映射配置')
        }
    }

    /**
     * 加载流程图模板
     */
    async loadFlowchartTemplates(): Promise<FlowchartTemplates> {
        try {
            return {
                version: "1.0.0",
                categories: [],
                description: '',
                lastUpdated: '',
                quickStart: [],
                patentSpecific: [],
                metadata: {
                    totalTemplates: 0,
                    complexity: {},
                    usage: {
                      mostUsed: [],
                      recommended: []
                    },
                    updates: {
                      lastTemplateAdded: '',
                      plannedUpdates: []
                    }
                  }
            } as FlowchartTemplates
        } catch (error) {
            console.error('Failed to load flowchart templates:', error)
            return {
                version: "1.0.0",
                categories: [],
                description: '',
                lastUpdated: '',
                quickStart: [],
                patentSpecific: [],
                metadata: {
                    totalTemplates: 0,
                    complexity: {},
                    usage: {
                      mostUsed: [],
                      recommended: []
                    },
                    updates: {
                      lastTemplateAdded: '',
                      plannedUpdates: []
                    }
                  }
            } as FlowchartTemplates
        }
    }

    /**
     * 获取特定图表类型的映射
     */
    getChartMapping(chartType: ChartType): ChartTypeMapping | undefined {
        if (!this.syntaxMapping) {
            console.warn('语法映射尚未加载，请先调用 loadMappings()')
            return undefined
        }

        return this.syntaxMapping.supportedCharts.find((chart: ChartTypeMapping) =>
            chart.type === chartType || chart.aliases?.includes(chartType)
        )
    }

    /**
     * 检查图表类型是否支持
     */
    isChartTypeSupported(chartType: string): boolean {
        const mapping = this.getChartMapping(chartType as ChartType)
        return mapping?.supported ?? false
    }

    /**
     * 获取支持的图表类型列表
     */
    getSupportedChartTypes(): string[] {
        if (!this.syntaxMapping) {
            return []
        }

        return this.syntaxMapping.supportedCharts
            .filter((chart: ChartTypeMapping) => chart.supported)
            .map((chart: ChartTypeMapping) => chart.type)
    }
}

async function getFlowchartTemplates(): Promise<FlowchartTemplate[]> {
    try {
        const templatesModule = await import('./templates/flowchart-templates.json')
        const templatesData = templatesModule.default

        // 简化处理，提取基础模板
        const templates: FlowchartTemplate[] = []

        if (templatesData.categories) {
            for (const category of templatesData.categories) {
                for (const template of category.templates || []) {
                    templates.push({
                        id: template.id,
                        name: template.name,
                        description: template.description,
                        category: category.name,
                        nodes: [], // 简化处理，先返回空数组
                        connections: []
                    })
                }
            }
        }

        return templates
    } catch (error) {
        console.error('Failed to load flowchart templates:', error)
        return []
    }
}

/**
 * 便捷函数：完整的编辑器工具集
 */

export class MermaidSyntax {
    private syntaxMappingLoader: SyntaxMappingLoader
    private mapping: MermaidSyntaxMapping
    private support_chart_types: string[]
    private chart_type: string

    constructor() {
        this.syntaxMappingLoader = new SyntaxMappingLoader()
        this.mapping = {} as MermaidSyntaxMapping // 初始化为空对象，稍后加载
        this.support_chart_types = []
        // this.support_chart_types = this.syntaxMappingLoader.getSupportedChartTypes()
        this.chart_type = '' // 默认图表类型为流程图
    }

    async init_mapping() {
        this.mapping  = await this.syntaxMappingLoader.loadMappings()
        this.support_chart_types = this.syntaxMappingLoader.getSupportedChartTypes()
        this.chart_type = this.support_chart_types[0] || 'flowchart' // 默认使用流程图
    }
    async get_templates() {
        return await getFlowchartTemplates()
    }

    MermaidSyntaxParser() {
        let fun = null
        switch (this.chart_type) {
            case 'flowchart':
                fun = new FlowChartMermaidSyntaxParser(this.mapping)
                break
            default:
                throw new Error(`Unsupported chart type: ${this.chart_type}`)
        }
        return fun
    }

    MermaidCodeGenerator() {
        let fun = null
        switch (this.chart_type) {
            case 'flowchart':
                fun = new FlowChartMermaidCodeGenerator(this.mapping)
                break
            default:
                throw new Error(`Unsupported chart type: ${this.chart_type}`)
        }
        return fun
    }

}

// 重新导出所有需要的类型
export type {
    MermaidNode,
    MermaidConnection,
    CompatibilityIssue,
    ChartType,
    MermaidSyntaxMapping,
    ChartTypeMapping,
    NodeTypeMapping,
    ConnectionTypeMapping,
    TemplateData,
    StyleConfig,
    StyleProperties,
    ComplexityAnalysis,
    ExportFormat,
    CodeDiff,
    CodeGenerationOptions,
    CodeGenerationResult,
    BatchGenerationResult
} from './types'


